package com.zygh.questionnairesurvey.server;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zygh.questionnairesurvey.common.CommonResult;
import com.zygh.questionnairesurvey.entity.UserInfo;
import com.zygh.questionnairesurvey.entity.UserMenu;
import com.zygh.questionnairesurvey.entity.vo.LoginVO;
import com.zygh.questionnairesurvey.entity.vo.UserVO;
import com.zygh.questionnairesurvey.mapper.UserInfoMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class LoginService {

    @Resource
    private TokenService tokenService;
    @Resource
    private UserService userService;
    @Resource
    private UserMenuService userMenuService;
    @Resource
    private UserInfoMapper userInfoMapper;

    public CommonResult login(LoginVO login) {

        String token = tokenService.getTokenByName(login.getUserName(), login.getPassWord());
        if (token != null) {
            UserInfo userInfo = userInfoMapper.selectOne(Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getUserName, login.getUserName()));
            if (userInfo.getStatus() == 1) {
                return new CommonResult().validateFailed("该系统已停止填报！");

            }
            UserVO user = userService.getUserInfo(login.getUserName());

            List<UserMenu> menuByUser = userMenuService.findMenuByUser(login.getUserName());
            user.setUserMenu(menuByUser);
            if (user != null) {
                if (menuByUser.size() > 0) {
                    user.setVisualScope(menuByUser.get(0).getVisualScope());
                }
                Map<String, Object> data = new HashMap<>(16);
                data.put("user", user);
                data.put("token", token);
                return new CommonResult().success(data);
            }
            return new CommonResult().validateFailed("该用户已禁用,请联系管理员！");
        }

        return new CommonResult().validateFailed("警号或密码错误！");
    }

    /**
     * 一键禁用用户/根据警号禁用单个用户
     * 警号
     * 状态（0 正常，1 删除）
     *
     * @param userInfo
     * @return
     */
    public CommonResult forbidden(UserInfo userInfo) {
        if (StringUtils.isNotBlank(userInfo.getUserName())) {
            int update = userInfoMapper.update(userInfo, Wrappers.<UserInfo>lambdaQuery()
                    .eq(UserInfo::getUserName, userInfo.getUserName()));
            if (update > 0) {
                return new CommonResult().success();
            }
            return new CommonResult().validateFailed("禁用失败！");
        }
        //一键禁用
        userInfo.setUserName(null);
        int update = userInfoMapper.update(userInfo, Wrappers.<UserInfo>lambdaQuery()
                .ne(UserInfo::getId, 1));
        if (update > 0) {
            return new CommonResult().success();
        }
        return new CommonResult().validateFailed("禁用失败！");
    }

}
